package com.fysports.web.kit.commons;

import com.jfinal.log.Log;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 时间工具类
 * Created by konbluesky
 * Date : 14-8-2 下午2:38
 * Project : JdmData_WebServer
 */
public class DateTimeKit {
    private static Log log = Log.getLog(DateTimeKit.class);

    public static final String pattern_date = "yyyy-MM-dd";
    public static final String pattern_datetime = "yyyy-MM-dd HH:mm:ss";
    public static final String pattern_time = "HH:mm:ss";
    public static final String pattern_datetimeMillisecond = "yyyy-MM-dd HH:mm:ss:SSS";
    public static final int time_day = 60 * 60 * 24;
    public static final int time_hour = 60 * 60;
    public static final int time_minutes = 60;


    /**
     * 主要是给jfinal使用，数据库只认java.sql.*
     *
     * @param date
     * @return
     */
    public static Timestamp getSqlTimestamp(Date date) {
        if (null == date) {
            date = new Date();
        }
        return getSqlTimestamp(date.getTime());
    }


    /**
     * 主要是给jfinal使用，数据库只认java.sql.*
     *
     * @param time
     * @return
     */
    public static Timestamp getSqlTimestamp(long time) {
        return new Timestamp(time);
    }


    /**
     * 获取当前时间
     *
     * @return
     */
    public static Date getDate() {
        return new Date();
    }


    /**
     * 获取当前时间的时间戳
     *
     * @return
     */
    public static long getDateByTime() {
        return new Date().getTime();
    }


    /**
     * 格式化
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }


    /**
     * 格式化
     *
     * @param date
     * @param parsePattern
     * @param returnPattern
     * @return
     */
    public static String format(String date, String parsePattern, String returnPattern) {
        return format(parse(date, parsePattern), returnPattern);
    }


    /**
     * 解析
     *
     * @param date
     * @param pattern
     * @return
     * @throws ParseException
     */
    public static Date parse(String date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        try {
            return format.parse(date);
        }
        catch (ParseException e) {
            log.error("DateTimeKit.parse异常：date值" + date + "，pattern值" + pattern);
            return null;
        }
    }


    /**
     * 两个日期的时间差，返回"X天X小时X分X秒"
     *
     * @param begin
     * @param end
     * @return
     */
    public static String getBetween(Date begin, Date end) {
        long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒

        long day = between / (24 * 3600);
        long hour = between % (24 * 3600) / 3600;
        long minute = between % 3600 / 60;
        long second = between % 60 / 60;

        StringBuffer sb = new StringBuffer();
        sb.append(day);
        sb.append("天");
        sb.append(hour);
        sb.append("小时");
        sb.append(minute);
        sb.append("分");
        sb.append(second);
        sb.append("秒");

        return sb.toString();
    }


    /**
     * 比较两个日期大小
     * result >0  : d1>d2
     * result <0   : d1<d2
     *
     * @return
     */
    public static long compareTwoDate(Date d1, Date d2) {
        return d1.getTime() - d2.getTime();
    }


    /**
     * 返回两个日期之间隔了多少小时
     *
     * @param start
     * @param end
     * @return
     */
    public static int getDateHourSpace(Date start, Date end) {
        int hour = (int) ((start.getTime() - end.getTime()) / 3600 / 1000);
        return hour;
    }


    /**
     * 返回两个日期之间隔了多少天
     *
     * @param start
     * @param end
     * @return
     */
    public static int getDateDaySpace(Date start, Date end) {
        int day = getDateHourSpace(start, end) / 24;
        return day;
    }


    /**
     * 得到某一天是星期几
     *
     * @param date 日期字符串
     * @return String 星期几
     */
    @SuppressWarnings("static-access") public static String getDateInWeek(String date) {
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        DateFormat format = DateFormat.getDateInstance();
        try {
            format.parse(date);
            Calendar c = format.getCalendar();
            int dayIndex = c.get(c.DAY_OF_WEEK) - c.SUNDAY;
            if (dayIndex < 0) {
                dayIndex = 0;
            }
            return weekDays[dayIndex];
        }
        catch (ParseException e) {
            return weekDays[0];
        }
    }


    /**
     * 日期减去多少个小时
     *
     * @param date
     * @param hourCount 多少个小时
     * @return
     */
    public static Date getDateReduceHour(Date date, long hourCount) {
        long time = date.getTime() - 3600 * 1000 * hourCount;
        Date dateTemp = new Date();
        dateTemp.setTime(time);
        return dateTemp;
    }


    /**
     * 日期区间分割
     *
     * @param start
     * @param end
     * @param splitCount
     * @return
     */
    public static List<Date> getDateSplit(Date start, Date end, long splitCount) {
        long startTime = start.getTime();
        long endTime = end.getTime();
        long between = endTime - startTime;

        long count = splitCount - 1l;
        long section = between / count;

        List<Date> list = new ArrayList<Date>();
        list.add(start);

        for (long i = 1l; i < count; i++) {
            long time = startTime + section * i;
            Date date = new Date();
            date.setTime(time);
            list.add(date);
        }

        list.add(end);

        return list;
    }


    /**
     * 返回两个日期之间隔了多少天，包含开始、结束时间
     *
     * @param start
     * @param end
     * @return
     */
    public static List<String> getDaySpaceDate(Date start, Date end) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(start);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(end);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        List<String> dateList = new LinkedList<String>();

        long dayCount =
                (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
        if (dayCount < 0) {
            return dateList;
        }

        dateList.add(format(fromCalendar.getTime(), pattern_date));

        for (int i = 0; i < dayCount; i++) {
            fromCalendar.add(Calendar.DATE, 1);// 增加一天

            dateList.add(format(fromCalendar.getTime(), pattern_date));
        }

        return dateList;
    }


    /**
     * 获取结束时间
     *
     * @param start
     * @param end
     * @return
     */
    public static Date startDate(Date start, int end) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        calendar.add(Calendar.DATE, end);// 明天1，昨天-1

        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date date = calendar.getTime();
        return date;
    }


    /**
     * 获取开始时间
     *
     * @param start
     * @return
     */
    public static Date endDate(Date start) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date date = calendar.getTime();
        return date;
    }


    /**
     * 获取当月第一天 时间为00:00:00
     * @return
     */
    public static Date monthlyFirstDay(Date d){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //将小时至0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        //将分钟至0
        calendar.set(Calendar.MINUTE, 0);
        //将秒至0
        calendar.set(Calendar.SECOND,0);
        //将毫秒至0
        calendar.set(Calendar.MILLISECOND, 0);
        //获得当前月第一天
        return calendar.getTime();
    }

    /**
     * 获取当月第一天 时间为23:59:59
     * @return
     */
    public static Date monthlyLastDay(Date d){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //将小时至0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        //将分钟至0
        calendar.set(Calendar.MINUTE, 0);
        //将秒至0
        calendar.set(Calendar.SECOND,0);
        //将毫秒至0
        calendar.set(Calendar.MILLISECOND, 0);
        //将当前月加1；
        calendar.add(Calendar.MONTH, 1);
        //在当前月的下一月基础上减去1毫秒
        calendar.add(Calendar.MILLISECOND, -1);
        return calendar.getTime();
    }


    public static void main(String[] args) {
        System.out.println(DateTimeKit.monthlyLastDay(new Date()));
        System.out.println(DateTimeKit.monthlyFirstDay(new Date()));
    }
}
